<template>
    <el-dialog
            :title="dialogTitle"
            v-model="dialogVisible"
            width="600px"
            :close-on-click-modal="false"
    >
        <el-form
                ref="formRef"
                :model="form"
                :rules="rules"
                label-width="120px"
                :disabled="type === 'view'"
        >
            <el-form-item label="礼券名称" prop="name">
                <el-input v-model="form.name"></el-input>
            </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择类型">
              <el-option label="折扣券" value="折扣券"></el-option>
              <el-option label="现金券" value="现金券"></el-option>
              <el-option label="满减券" value="满减券"></el-option>
            </el-select>
          </el-form-item>
            <el-form-item label="面值" prop="value">
                <el-input-number v-model="form.value" :precision="2"></el-input-number>
            </el-form-item>
            <el-form-item label="有效期" prop="validDates">
                <el-date-picker
                        v-model="form.validDates"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                >
                </el-date-picker>
            </el-form-item>

            <!-- 使用条件 -->
            <el-form-item label="使用条件">
                <div v-for="(condition, index) in form.usageConditions" :key="index">
                    <el-input v-model="form.usageConditions[index]" style="width: 80%">
                        <template #append>
                            <el-button @click="removeCondition(index)">删除</el-button>
                        </template>
                    </el-input>
                </div>
                <el-button @click="addCondition">添加使用条件</el-button>
            </el-form-item>

            <!-- 适用范围 -->
            <el-form-item label="适用范围">
                <div v-for="(scope, index) in form.applicableScope" :key="index">
                    <el-input v-model="form.applicableScope[index]" style="width: 80%">
                        <template #append>
                            <el-button @click="removeScope(index)">删除</el-button>
                        </template>
                    </el-input>
                </div>
                <el-button @click="addScope">添加适用范围</el-button>
            </el-form-item>
        </el-form>

        <template #footer>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit" v-if="type !== 'view'">
                确定
            </el-button>
        </template>
    </el-dialog>
</template>

<script setup>
    import { ref, computed, watch } from 'vue'
    import { ElMessage } from 'element-plus'
    import { addCoupons, updateCoupons } from '@/api/coupons'

    const props = defineProps({
        visible: Boolean,
        type: String,
        couponData: Object
    })

    const emit = defineEmits(['update:visible', 'success'])

    const dialogVisible = computed({
        get: () => props.visible,
        set: (val) => emit('update:visible', val)
    })

    const dialogTitle = computed(() => {
        const titles = {
            add: '新增礼券',
            edit: '修改礼券',
            view: '查看礼券'
        }
        return titles[props.type]
    })

    const formRef = ref(null)
    const form = ref({
        name: '',
        type: '',
        value: 0,
        validDates: [],
        usageConditions: [],
        applicableScope: [],
        status: 'published'
    })

    const rules = {
        name: [{ required: true, message: '请输入礼券名称', trigger: 'blur' }],
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        value: [{ required: true, message: '请输入面值', trigger: 'blur' }],
        validDates: [{ required: true, message: '请选择有效期', trigger: 'change' }]
    }

    // 监听couponData变化
    watch(
        () => props.couponData,
        (newVal) => {
            if (newVal) {
                form.value = {
                    ...newVal,
                    validDates: [newVal.validFrom, newVal.validUntil],
                    usageConditions: JSON.parse(newVal.usageConditions || '[]'),
                    applicableScope: JSON.parse(newVal.applicableScope || '[]')
                }
            } else {
                form.value = {
                    name: '',
                    type: '',
                    value: 0,
                    validDates: [],
                    usageConditions: [],
                    applicableScope: [],
                    status: 'published'
                }
            }
        },
        { immediate: true }
    )

    // 添加/删除使用条件
    const addCondition = () => {
        form.value.usageConditions.push('')
    }

    const removeCondition = (index) => {
        form.value.usageConditions.splice(index, 1)
    }

    // 添加/删除适用范围
    const addScope = () => {
        form.value.applicableScope.push('')
    }

    const removeScope = (index) => {
        form.value.applicableScope.splice(index, 1)
    }

    // 提交表单
    const handleSubmit = async () => {
        if (!formRef.value) return

        await formRef.value.validate()

        const submitData = {
            ...form.value,
            validFrom: form.value.validDates[0],
            validUntil: form.value.validDates[1],
            usageConditions: JSON.stringify(form.value.usageConditions),
            applicableScope: JSON.stringify(form.value.applicableScope)
        }

        try {
            if (props.type === 'add') {
                await addCoupons(submitData)
                ElMessage.success('添加成功')
            } else {
                await updateCoupons(submitData)
                ElMessage.success('修改成功')
            }
            emit('success')
        } catch (error) {
            ElMessage.error(props.type === 'add' ? '添加失败' : '修改失败')
        }
    }
</script>